package com.benefm.multipar.pad.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.*;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class HealthDashboardView extends View {
    // 主仪表盘参数
    private Paint mainArcPaint, mainScalePaint, mainValuePaint, centerPaint;
    private RectF mainArcRect;
    private int mainValue = 82;
    private int maxValue = 100;
    private int centerX, centerY;
    private float radius;
    private float startAngle = 135f;
    private float sweepAngle = 270f;

    // 小型数据面板
    private List<MiniPanel> miniPanels;

    // 背景和颜色
    private int backgroundColor = Color.parseColor("#0C0F15");
    private int mainArcColor = Color.parseColor("#2D3250");
    private int mainFillColor = Color.parseColor("#29B6F6");
    private int criticalColor = Color.parseColor("#F44336");
    private int textColor = Color.parseColor("#E0F7FA");

    // 动画
    private ValueAnimator mainValueAnimator;
    private Handler dataHandler = new Handler();
    private Random random = new Random();

    public HealthDashboardView(Context context) {
        super(context);
        init(null);
    }

    public HealthDashboardView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        // 主弧线画笔
        mainArcPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mainArcPaint.setStyle(Paint.Style.STROKE);
        mainArcPaint.setStrokeWidth(18f);
        mainArcPaint.setStrokeCap(Paint.Cap.ROUND);

        // 主刻度画笔
        mainScalePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mainScalePaint.setStrokeWidth(3f);
        mainScalePaint.setColor(Color.WHITE);

        // 主值画笔
        mainValuePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mainValuePaint.setTextSize(64f);
        mainValuePaint.setColor(Color.WHITE);
        mainValuePaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
        mainValuePaint.setTextAlign(Paint.Align.CENTER);

        // 中心画笔
        centerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        centerPaint.setStyle(Paint.Style.FILL);
        centerPaint.setColor(Color.parseColor("#1E1E2D"));

        // 创建小型数据面板
        createMiniPanels();

        mainArcRect = new RectF();
    }

    private void createMiniPanels() {
        miniPanels = new ArrayList<>();

        // 添加不同类型的小型面板
        miniPanels.add(new MiniPanel("Blood", "82%", Color.parseColor("#F44336")));
        miniPanels.add(new MiniPanel("Oxygen", "98%", Color.parseColor("#29B6F6")));
        miniPanels.add(new MiniPanel("Pulse", "72", Color.parseColor("#7E57C2")));
        miniPanels.add(new MiniPanel("Temp", "36.6°C", Color.parseColor("#FF9800")));
        miniPanels.add(new MiniPanel("Resp", "16", Color.parseColor("#4CAF50")));
        miniPanels.add(new MiniPanel("BPM", "66", Color.parseColor("#E91E63")));
        miniPanels.add(new MiniPanel("SO2", "99%", Color.parseColor("#00BCD4")));
        miniPanels.add(new MiniPanel("EMI", "24", Color.parseColor("#FFC107")));
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        centerX = w / 2;
        centerY = h / 2;
        radius = Math.min(w, h) * 0.45f;

        // 主弧线区域
        mainArcRect.set(
                centerX - radius,
                centerY - radius,
                centerX + radius,
                centerY + radius
        );

        // 更新小型面板位置
        float panelRadius = radius * 0.6f;
        float angleStep = 360f / miniPanels.size();
        float currentAngle = 0f;

        for (MiniPanel panel : miniPanels) {
            float angle = (float) Math.toRadians(currentAngle);
            panel.x = centerX + (float) (panelRadius * Math.cos(angle));
            panel.y = centerY + (float) (panelRadius * Math.sin(angle));
            panel.radius = radius * 0.2f;
            currentAngle += angleStep;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 绘制背景
        drawBackground(canvas);

        // 绘制主仪表盘
        drawMainDashboard(canvas);

        // 绘制小型面板
        drawMiniPanels(canvas);

        // 绘制中心文本
        drawCenterText(canvas);
    }

    private void drawBackground(Canvas canvas) {
        canvas.drawColor(backgroundColor);

        // 绘制精细的点状背景网格
        Paint gridPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        gridPaint.setColor(Color.parseColor("#1A1A2E"));

        for (int i = 0; i < getWidth(); i += 20) {
            for (int j = 0; j < getHeight(); j += 20) {
                canvas.drawCircle(i, j, 1, gridPaint);
            }
        }
    }

    private void drawMainDashboard(Canvas canvas) {
        // 绘制主弧线背景
        mainArcPaint.setColor(mainArcColor);
        canvas.drawArc(mainArcRect, startAngle, sweepAngle, false, mainArcPaint);

        // 计算血氧值对应的角度
        float valueAngle = startAngle + (sweepAngle * mainValue / maxValue);

        // 绘制已填充弧线
        mainArcPaint.setColor(mainValue > 85 ? criticalColor : mainFillColor);
        canvas.drawArc(mainArcRect, startAngle, sweepAngle * mainValue / maxValue, false, mainArcPaint);

        // 绘制刻度
        drawScales(canvas);

        // 绘制标记点 (不去掉点，去掉射线)
        float angleRad = (float) Math.toRadians(valueAngle);
        float pointX = centerX + (radius - mainArcPaint.getStrokeWidth() / 2) * (float) Math.cos(angleRad);
        float pointY = centerY + (radius - mainArcPaint.getStrokeWidth() / 2) * (float) Math.sin(angleRad);

        Paint pointPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        pointPaint.setStyle(Paint.Style.FILL);
        pointPaint.setColor(Color.WHITE);
        canvas.drawCircle(pointX, pointY, 10, pointPaint);
    }

    private void drawScales(Canvas canvas) {
        int majorScales = 5; // 主刻度数量
        float scaleLength = 15f;

        for (int i = 0; i <= majorScales; i++) {
            float value = i * (maxValue / majorScales);
            float angle = startAngle + (sweepAngle * i / majorScales);
            float angleRad = (float) Math.toRadians(angle);

            // 计算位置
            float startX = (float) (centerX + radius * Math.cos(angleRad));
            float startY = (float) (centerY + radius * Math.sin(angleRad));
            float endX = (float) (centerX + (radius - scaleLength) * Math.cos(angleRad));
            float endY = (float) (centerY + (radius - scaleLength) * Math.sin(angleRad));

            // 绘制刻度线
            canvas.drawLine(startX, startY, endX, endY, mainScalePaint);

            // 绘制刻度值
            if (i > 0 && i < majorScales) {
                float textRadius = radius - scaleLength - 25f;
                float textX = (float) (centerX + textRadius * Math.cos(angleRad));
                float textY = (float) (centerY + textRadius * Math.sin(angleRad)) + 12;

                Paint textPaint = new Paint(mainScalePaint);
                textPaint.setTextSize(22f);
                textPaint.setTextAlign(Paint.Align.CENTER);
                canvas.drawText(String.valueOf((int) value), textX, textY, textPaint);
            }
        }

        // 绘制标题
        Paint titlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        titlePaint.setTextSize(28f);
        titlePaint.setColor(textColor);
        titlePaint.setTextAlign(Paint.Align.CENTER);

        float titleAngle = startAngle + sweepAngle / 2;
        float titleAngleRad = (float) Math.toRadians(titleAngle);
        float titleRadius = radius * 1.15f;
        float titleX = centerX + titleRadius * (float) Math.cos(titleAngleRad);
        float titleY = centerY + titleRadius * (float) Math.sin(titleAngleRad);

        canvas.drawText("BLOOD OXYGEN", titleX, titleY, titlePaint);
    }

    private void drawMiniPanels(Canvas canvas) {
        for (MiniPanel panel : miniPanels) {
            // 绘制圆形背景
            Paint panelBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            panelBgPaint.setStyle(Paint.Style.FILL);
            panelBgPaint.setColor(Color.parseColor("#15182B"));
            canvas.drawCircle(panel.x, panel.y, panel.radius, panelBgPaint);

            // 绘制圆形边框
            Paint panelBorderPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            panelBorderPaint.setStyle(Paint.Style.STROKE);
            panelBorderPaint.setStrokeWidth(3f);
            panelBorderPaint.setColor(Color.parseColor("#2E324A"));
            canvas.drawCircle(panel.x, panel.y, panel.radius, panelBorderPaint);

            // 绘制标题
            Paint titlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            titlePaint.setTextSize(panel.radius * 0.3f);
            titlePaint.setColor(Color.parseColor("#B0BEC5"));
            titlePaint.setTextAlign(Paint.Align.CENTER);
            canvas.drawText(panel.title, panel.x, panel.y - panel.radius * 0.3f, titlePaint);

            // 绘制值
            Paint valuePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            valuePaint.setTextSize(panel.radius * 0.4f);
            valuePaint.setColor(panel.valueColor);
            valuePaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
            valuePaint.setTextAlign(Paint.Align.CENTER);
            canvas.drawText(panel.value, panel.x, panel.y + panel.radius * 0.2f, valuePaint);
        }
    }

    private void drawCenterText(Canvas canvas) {
        // 绘制中心圆形背景
        float centerRadius = radius * 0.3f;
        canvas.drawCircle(centerX, centerY, centerRadius, centerPaint);

        // 绘制中心圆形边框
        Paint borderPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        borderPaint.setStyle(Paint.Style.STROKE);
        borderPaint.setStrokeWidth(4f);
        borderPaint.setColor(Color.parseColor("#292D47"));
        canvas.drawCircle(centerX, centerY, centerRadius, borderPaint);

        // 绘制中心大值
        Paint bigValuePaint = new Paint(mainValuePaint);
        bigValuePaint.setTextSize(radius * 0.3f);
        bigValuePaint.setColor(Color.WHITE);
        canvas.drawText(String.valueOf(mainValue), centerX, centerY - radius * 0.1f, bigValuePaint);

        // 绘制中心单位
        Paint unitPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        unitPaint.setTextSize(radius * 0.12f);
        unitPaint.setColor(Color.parseColor("#7986CB"));
        canvas.drawText("OXYGEN %", centerX, centerY + radius * 0.15f, unitPaint);

        // 绘制状态图标 (心形)
        drawHeartIcon(canvas);
    }

    private void drawHeartIcon(Canvas canvas) {
        float heartSize = radius * 0.15f;
        Path path = new Path();

        // 从顶部中心开始
        path.moveTo(centerX, centerY - heartSize * 0.7f);

        // 绘制左曲线
        path.cubicTo(
                centerX - heartSize * 0.6f, centerY - heartSize * 0.4f,
                centerX - heartSize * 0.9f, centerY + heartSize * 0.2f,
                centerX - heartSize * 0.4f, centerY + heartSize * 0.4f
        );

        // 绘制右曲线
        path.cubicTo(
                centerX, centerY + heartSize * 0.1f,
                centerX + heartSize * 0.4f, centerY + heartSize * 0.4f,
                centerX + heartSize * 0.4f, centerY + heartSize * 0.4f
        );

        path.cubicTo(
                centerX + heartSize * 0.9f, centerY + heartSize * 0.2f,
                centerX + heartSize * 0.6f, centerY - heartSize * 0.4f,
                centerX, centerY - heartSize * 0.7f
        );

        path.close();

        Paint heartPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        heartPaint.setStyle(Paint.Style.FILL);
        heartPaint.setColor(criticalColor);
        canvas.drawPath(path, heartPaint);
    }

    // 设置主血氧值 (带动画)
    public void setBloodOxygen(int value) {
        if (value > maxValue) value = maxValue;
        if (value < 0) value = 0;

        if (mainValueAnimator != null && mainValueAnimator.isRunning()) {
            mainValueAnimator.cancel();
        }

        mainValueAnimator = ValueAnimator.ofInt(mainValue, value);
        mainValueAnimator.setDuration(1200);
        mainValueAnimator.addUpdateListener(animation -> {
            mainValue = (int) animation.getAnimatedValue();
            invalidate();
        });
        mainValueAnimator.start();
    }

    // 更新小型面板的值
    public void updateMiniPanelValue(int index, String value) {
        if (index >= 0 && index < miniPanels.size()) {
            miniPanels.get(index).value = value;
            invalidate();
        }
    }

    // 随机更新所有面板的值 (演示用)
    public void randomizeValues() {
        // 更新主血氧值 (70-99)
        setBloodOxygen(70 + random.nextInt(30));

        // 更新小型面板的值
        for (int i = 0; i < miniPanels.size(); i++) {
            MiniPanel panel = miniPanels.get(i);
            if (panel.title.equals("Blood")) {
                updateMiniPanelValue(i, (82 + random.nextInt(5)) + "%");
            } else if (panel.title.equals("Oxygen")) {
                updateMiniPanelValue(i, (98 - random.nextInt(3)) + "%");
            } else if (panel.title.equals("Pulse")) {
                updateMiniPanelValue(i, String.valueOf(72 + random.nextInt(10)));
            } else if (panel.title.equals("Temp")) {
                updateMiniPanelValue(i, "36." + random.nextInt(3) + "°C");
            } else {
                updateMiniPanelValue(i, String.valueOf(random.nextInt(20) + 80) + "%");
            }
        }
    }

    // 开始模拟数据更新
    public void startDataSimulation() {
        dataHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                randomizeValues();
                dataHandler.postDelayed(this, 2000);
            }
        }, 2000);
    }

    // 停止数据模拟
    public void stopDataSimulation() {
        dataHandler.removeCallbacksAndMessages(null);
    }

    // 小型数据面板类
    private static class MiniPanel {
        String title;
        String value;
        int valueColor;
        float x, y;
        float radius;

        MiniPanel(String title, String value, int valueColor) {
            this.title = title;
            this.value = value;
            this.valueColor = valueColor;
        }
    }
}